package com.ydj.manager;


import lombok.extern.slf4j.Slf4j;
import org.hibernate.annotations.common.util.impl.LoggerFactory;
import org.jboss.logging.Logger;

/**
 *
 */
@Slf4j
public abstract class ThreadPoolTask<T> implements Runnable, Comparable<ThreadPoolTask<T>> {

    protected String threadName;
    protected T parameter;

    protected long postTime;
    protected int priority;

    public abstract void doTask(T parameter);

    public ThreadPoolTask(String name) {
        threadName = name;
    }

    public String getName() {
        return (threadName == null ? "" : threadName);
    }

    public ThreadPoolTask setParameter(T parameter) {
        this.parameter = parameter;
        return this;
    }

    @Override
    public void run() {
        Thread.currentThread().setName(threadName);
        log.info("异步任务 {} 开始", threadName);
        doTask(parameter);
        log.info("异步任务 {} 结束", threadName);
    }

    @Override
    public int compareTo(ThreadPoolTask<T> o) {
        int gap = o.priority - this.priority;
        if (gap != 0) {
            return gap;
        }
        long timeGap = o.postTime - this.postTime;
        if (timeGap > 0) {
            return 1;
        } else if (timeGap < 0) {
            return -1;
        } else {
            return 0;
        }
    }

    @Override
    public String toString() {
        return getName();
    }

    public void post(ThreadPoolManager.PoolType poolType) {
        post(poolType, Thread.NORM_PRIORITY);
    }

    public void post(ThreadPoolManager.PoolType poolType, int priority) {
        this.priority = priority;
        ThreadPoolManager.postTask(this, poolType);
    }

}
